//
//  SocialViewController.swift
//  BaseSwift
//
//  Created by gh on 2019/10/9.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import PYSearch

class SocialViewController: UIViewController {

    let publishBtn = UIButton()

    var page = 1
    var type:String = "social"
    
    var dataArray:Array<TopPic> = Array()
    
    func seachTopics(title: String){
        
        API.socialList(params: ["title":title]) { (result) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            
            let pageVo = result as! Page<TopPic>
            
            if self.page == 1{
                
                self.dataArray = pageVo.list

            }else{
                
                for item in pageVo.list {
                    
                    self.dataArray.append(item)
                }
            }
            
            if pageVo.list.count < 20{
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            
        }
        
    }
    func sendRequest(){
        
        API.socialList(params: ["page":page.description]) { (result) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            
            let pageVo = result as! Page<TopPic>
            
            if self.page == 1{
                
                self.dataArray = pageVo.list

            }else{
                
                for item in pageVo.list {
                    
                    self.dataArray.append(item)
                }
            }
            
            if pageVo.list.count < 20{
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            
        }
        
    }
    func sendRequestForMe(){
        
        API.myTopicList(params: ["page":page.description]) { (result) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            
            let pageVo = result as! Page<TopPic>
            
            if self.page == 1{
                
                self.dataArray = pageVo.list

            }else{
                
                for item in pageVo.list {
                    
                    self.dataArray.append(item)
                }
            }
            
            if pageVo.list.count < 20{
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            
        }
        
    }
    
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(UINib.init(nibName: "SocialCell", bundle: nil), forCellReuseIdentifier: "SocialCell")
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        
        self.view.backgroundColor = UIColor.backgroundColor
        
        self.view.addSubview(tableView)
        let _ = tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: HT_StatusBarAndNavigationBarHeight, left: 0, bottom: HT_TabbarSafeBottomMargin, right: 0))
        
        
        let header = MJRefreshNormalHeader.init {
            
            self.page = 1
            self.sendRequest()
        }
        header?.stateLabel.isHidden = true
        header?.lastUpdatedTimeLabel.isHidden = true
        self.tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter.init {

            self.page += 1
            self.sendRequest()
        }
        self.tableView.mj_footer = footer
        

        
        if self.type == "me"{
            
            self.navigationView.setTitle("我的帖子")
            self.sendRequestForMe()

        }else{
            
            self.navigationView.setTitle("微社区")
            view.addSubview(publishBtn)
            publishBtn.setImage(UIImage(named: "微社区(1)"), for: .normal)
            let _ = publishBtn.imageView?.sd_layout()?.widthIs(60)!.heightIs(60)!.centerXEqualToView(publishBtn)!.centerYEqualToView(publishBtn)
            publishBtn.sd_cornerRadius = 30
            let _ = publishBtn.sd_layout()?.widthIs(60)!.heightIs(60)!.centerXEqualToView(view)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin+10)
            view.bringSubviewToFront(publishBtn)
            publishBtn.addTarget(self, action: #selector(publishClick), for: .touchUpInside)
            
            self.navigationView.addRightButton(with: UIImage(named: "search_11")) { (view) in
                
                self.startSearch()
                
            }
            self.sendRequest()


        }
    }
    

    @objc func publishClick(){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }
        
        PUSH(from: self, to: PublishViewController())
    }
    
    func startSearch(){
        
        let searVC = PYSearchViewController.init(hotSearches: [], searchBarPlaceholder: "请输入帖子标题") { (vc, bar, str) in
            
            
            if str?.isEmpty == true{
                
                ToastUtil.show(msg: "请输入帖子标题")
                return
            }
            

            vc?.dismiss(animated: true, completion: {
                
                //self.sendRequest()
                self.seachTopics(title: str!)

            })
            
        }
    
        searVC?.searchHistoriesCachePath = BZHttpFileHelper.getTopCachePath()
        let nav = UINavigationController(rootViewController: searVC!)

        self.present(nav, animated: true) {
            
            
        }
    }

}
extension SocialViewController:UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate{
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let yOffset = scrollView.contentOffset.y
        print("\(yOffset)")
        if yOffset > HT_StatusBarAndNavigationBarHeight {
            
            self.publishBtn.isHidden = true
        }
        if yOffset <= 0 {
            
            self.publishBtn.isHidden = false
        }

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let mod = self.dataArray.get(at: indexPath.row)
        if mod?.userPostingImgList.count == 0 {
            
            return 155+10
            
            
        }else{
            
            return 190+10

        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SocialCell") as! SocialCell
        let mod = self.dataArray.get(at: indexPath.row)
        cell.setModel(mod: mod!)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let mod = self.dataArray.get(at: indexPath.row)

        API.socialDetail(params: ["pId":mod!.id!]) { (result) in
            
            
            let dvc = SocialDetailVC()
            dvc.topPic = (result as! TopPic)
            PUSH(from: self, to: dvc)
        }

        
    }

    
    
}
